/**
 * 
 */
package com.cipe.cmrs.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cipe.cmrs.model.Partner;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.util.DateUtil;
import com.cipe.cmrs.util.UserUtil;

/**
 * @author Incepio
 * 
 */
@Service
@Transactional
public class PartnerService extends BaseService<Partner> {

	@Autowired
	private UserService userService;
	@Autowired
	private CipeprojectService cipeprojectService;
	
	public Partner savePartner(Partner partner, Integer userId) {
		if (partner != null) {
			User user = UserUtil.INSTANCE.getCurrentUser();
			Partner dbPartner = findById(partner.getId());
			if (dbPartner == null) {
				dbPartner = new Partner();
				dbPartner.setCreatedBy(user);
				dbPartner.setCreationDate(DateUtil.getCurrentDate());
			}
			dbPartner.setPartnerName(partner.getPartnerName().trim());
			dbPartner.setUrl(partner.getUrl());
			dbPartner.setAddress1(partner.getAddress1());
			dbPartner.setAddress2(partner.getAddress2());
			dbPartner.setCity(partner.getCity());
			dbPartner.setState(partner.getState() != null && partner.getState().getId() != null ? partner.getState() : null);
			dbPartner.setZipCode(partner.getZipCode());
			dbPartner.setCountry(partner.getCountry().getId() != null ? partner.getCountry() : null );
			dbPartner.setPhone(partner.getPhone());
			dbPartner.setFax(partner.getFax());
			dbPartner.setEmail(partner.getEmail());
			String type = partner.getType();
			if (!type.equalsIgnoreCase("0")) {
				dbPartner.setType(type);
			}
			String status = partner.getStatus();
			if (!status.equalsIgnoreCase("0")) {
				dbPartner.setStatus(status);
			}
			dbPartner.setContactFirstName(partner.getContactFirstName());
			dbPartner.setContactMiddleName(partner.getContactMiddleName());
			dbPartner.setContactLastName(partner.getContactLastName());
			dbPartner.setContactEmail(partner.getContactEmail());
			dbPartner.setContactFax(partner.getContactFax());
			dbPartner.setContactPhone(partner.getContactPhone());
			dbPartner.setUpdatedBy(user);
			dbPartner.setUpdationDate(DateUtil.getCurrentDate());
			
			/*if(dbPartner.getId() == null || dbPartner.getId() == 0) {
				dbPartner = persist(dbPartner);  // for creating the entity
			} else */{
				dbPartner = merge(dbPartner); // for merging (merge does not feed automatically the pk if it is null)
			}	
			
//			Cipeproject cipeproject = cipeprojectService.findById(partner.getCipeprojectId());
//			cipeproject.setPartner(dbPartner);
//			cipeprojectService.merge(cipeproject);
			
			return dbPartner;
		}
		return null;
	}
}
